package com.ruoyi.web.controller.api;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.exa.domain.*;
import com.ruoyi.exa.service.*;
import com.ruoyi.web.controller.api.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Api("对外考试相关接口")
@RestController
@RequestMapping("/api/exa")
public class ApiExaController extends BaseController {

    @Autowired
    private IExaBitchUserService exaBitchUserService;
    @Autowired
    private IExaQuestionOptionsService exaQuestionOptionsService;
    @Autowired
    private IExaQuestionBankService exaQuestionBankService;
    @Autowired
    private IExaParperService exaParperService;
    @Autowired
    private IExaClassQuestionsService exaClassQuestionsService;
    @Autowired
    private IExaParperClassService exaParperClassService;
    @Autowired
    private IExaBitchUserQuestionsService exaBitchUserQuestionsService;
    @Autowired
    private IExaParperClassService iExaParperClassService;


    /**
     * 查询批次员工列表
     */
    @ApiOperation("查询批次员工列表")
    @GetMapping("/clientUserList")
    public TableDataInfo clientUserList(ExaBitchUser exaBitchUser)
    {
        startPage();
        //获取当前登录用户
        SysUser user = getLoginUser().getUser();
        exaBitchUser.setUserId(user.getUserId());
        List<ExaBitchUser> list = exaBitchUserService.selectExaBitchUserAllList(exaBitchUser);
        return getDataTable(list);
    }

    @ApiOperation("查看试卷所有信息")
    @GetMapping("/getParperDetails")
    public R getParperDetails(long parperId,Long bitchId,Long userId) {

        //获取试卷信息
        ExaParper exaParper = exaParperService.selectExaParperById(parperId);
        ExaParperClassVo exaParperClassVo = new ExaParperClassVo();


        //获取所有的class
        ExaParperClass exaParperClassParam = new ExaParperClass();
        exaParperClassParam.setParperId(parperId);
        List<ExaParperClass> exaParperClassList = exaParperClassService.selectExaParperClassList(exaParperClassParam);

        List<ExaClassVo> ExaClassVos = new ArrayList<>();

        exaParperClassList.forEach(item->{
        //根据classId获取class详情
            ExaClassVo exaClassVo = new ExaClassVo();

            ExaParperClass exaParperClass = exaParperClassService.selectExaParperClassById(item.getId());
            //根据classId获取class下的所有question
            ExaClassQuestions exaClassQuestions = new ExaClassQuestions();
            exaClassQuestions.setClassId(item.getId());
            List<ExaClassQuestions> exaClassQuestionsList = exaClassQuestionsService.selectExaClassQuestionsList(exaClassQuestions);
            //打乱题目顺序
            Collections.shuffle(exaClassQuestionsList);
            exaClassVo.setExaParperClass(exaParperClass);
            List<ExaClassQuestionsVo> exaClassQuestionsVos = new ArrayList<>();

            exaClassQuestionsList.forEach(item1-> {
                ExaClassQuestionsVo exaClassQuestionsVo = new ExaClassQuestionsVo();
                exaClassQuestionsVo.setExaClassQuestions(item1);
                //根据questionId获取question详情
                ExaQuestionBankVo exaQuestionBankVo = new ExaQuestionBankVo();
                ExaQuestionBank exaQuestionBank = exaQuestionBankService.selectExaQuestionBankById(item1.getQuestionId());
                //根据questionId获取question下的所有options
                ExaQuestionOptions exaQuestionOptions = new ExaQuestionOptions();
                exaQuestionOptions.setQuestionId(item1.getQuestionId());
                List<ExaQuestionOptions> exaQuestionOptionsList = exaQuestionOptionsService.selectExaQuestionOptionsList(exaQuestionOptions);
                //获取之前提交过的答题卡------------中途退出再回来
                if(bitchId!=null&&userId!=null){
                    ExaBitchUserQuestions exaBitchUserQuestions = new ExaBitchUserQuestions();
                    exaBitchUserQuestions.setUserId(userId);
                    exaBitchUserQuestions.setParperId(parperId);
                    exaBitchUserQuestions.setBitchId(bitchId);
                    List<ExaBitchUserQuestions> exaBitchUserQuestionsList = exaBitchUserQuestionsService.selectExaBitchUserQuestionsList(exaBitchUserQuestions);
                    if(exaBitchUserQuestionsList.size()>0){
                        //查询批次员工中途退出剩余时间
                        ExaBitchUser exaBitchUser = exaBitchUserService.selectExaBitchUserByQuit(bitchId, userId, parperId);
                        if(exaBitchUser.getIsQuit()==1){
                            exaParper.setAnsweringTime(exaBitchUser.getRemainingTime());
                        }
                        List<ExaBitchUserQuestions> collect = exaBitchUserQuestionsList.stream().filter(q -> q.getQuestionId().equals(item1.getQuestionId())).collect(Collectors.toList());
                        for (ExaQuestionOptions questionOptions:exaQuestionOptionsList){
                            for(ExaBitchUserQuestions questions: collect){
                                if(questionOptions.getId().equals(questions.getOptionsId())){
                                    questionOptions.setOldQuestion(true);
                                    if(questions.getContent()!=null){
                                        questionOptions.setOldContent(questions.getContent());
                                    }
                                }
                            }
                        }
                    }
                }
                exaQuestionBankVo.setExaQuestionBank(exaQuestionBank);
                exaQuestionBankVo.setExaQuestionOptionsList(exaQuestionOptionsList);
                exaClassQuestionsVo.setExaQuestionBankVo(exaQuestionBankVo);

                exaClassQuestionsVos.add(exaClassQuestionsVo);
            });
            exaClassVo.setExaClassQuestionsList(exaClassQuestionsVos);
            ExaClassVos.add(exaClassVo);
        });
        exaParperClassVo.setExaClassVoList(ExaClassVos);
        exaParperClassVo.setExaParper(exaParper);
        return R.ok(exaParperClassVo);

    }

    /**
     * 首页底部菜单栏列表
     */
    @ApiOperation("根据登录用户获取考核列表")
    @GetMapping("/getExabitchUserList")
    public List<ExaBitchUser> baseTabbarList()
    {
        //获取登录用户信息
        SysUser sysUser = getLoginUser().getUser();
        ExaBitchUser exaBitchUser = new ExaBitchUser();
        exaBitchUser.setUserId(sysUser.getUserId());
        List<ExaBitchUser> list = exaBitchUserService.selectExaBitchUserList(exaBitchUser);
        return list;
    }




    /**
     * 保存题库试题及选项
     */
    @ApiOperation("保存或编辑题库试题及选项")
    @PostMapping("/addorUpdateExaQuestionBank")
    @Transactional
    public R addorUpdateExaQuestionBank(@RequestBody ExaQuestionBankVo exaQuestionBankVo)
    {
        if(exaQuestionBankVo.getExaQuestionBank().getId() != null){
            //编辑
            exaQuestionBankService.updateExaQuestionBank(exaQuestionBankVo.getExaQuestionBank());
            //删除问题的所有选项
            exaQuestionOptionsService.deleteExaQuestionOptionsByQuestionId(exaQuestionBankVo.getExaQuestionBank().getId());
            for (ExaQuestionOptions exaQuestionOptions : exaQuestionBankVo.getExaQuestionOptionsList()) {
                exaQuestionOptions.setQuestionId(exaQuestionBankVo.getExaQuestionBank().getId());
                exaQuestionOptionsService.insertExaQuestionOptions(exaQuestionOptions);
            }
        }else{
            //新增
            exaQuestionBankService.insertExaQuestionBank(exaQuestionBankVo.getExaQuestionBank());
            for (ExaQuestionOptions exaQuestionOptions : exaQuestionBankVo.getExaQuestionOptionsList()) {
                exaQuestionOptions.setQuestionId(exaQuestionBankVo.getExaQuestionBank().getId());
                exaQuestionOptionsService.insertExaQuestionOptions(exaQuestionOptions);
            }
        }

        return R.ok();
    }


    /**
     *保存或编辑试卷管理
     */
    @ApiOperation("保存或编辑试卷管理")
    @PostMapping("/addorUpdateExaParper")
    @Transactional
    public R addorUpdateExaParper(@RequestBody ExaParperClassVo exaParperClassVo) {

        if(exaParperClassVo.getExaParper().getId()!= null){
            //编辑
            exaParperService.updateExaParper(exaParperClassVo.getExaParper());
            //删除题目下的所有试题
            exaParperClassVo.getExaClassVoList().forEach(item->{
                exaClassQuestionsService.deleteExaClassQuestionsByClassId(item.getExaParperClass().getId());
            });
            //删除试卷下的所有题目
            exaParperClassService.deleteExaParperClassByParperId(exaParperClassVo.getExaParper().getId());

            exaParperClassVo.getExaClassVoList().forEach(item->{
                item.getExaParperClass().setParperId(exaParperClassVo.getExaParper().getId());
                exaParperClassService.insertExaParperClass(item.getExaParperClass());
                item.getExaClassQuestionsList().forEach(item1->{
                    item1.getExaClassQuestions().setClassId(item.getExaParperClass().getId());
                    exaClassQuestionsService.insertExaClassQuestions(item1.getExaClassQuestions());
                });
            });

        }else{
            //新增
            exaParperService.insertExaParper(exaParperClassVo.getExaParper());
            exaParperClassVo.getExaClassVoList().forEach(item->{
                item.getExaParperClass().setParperId(exaParperClassVo.getExaParper().getId());
                exaParperClassService.insertExaParperClass(item.getExaParperClass());
                item.getExaClassQuestionsList().forEach(item1->{
                    item1.getExaClassQuestions().setClassId(item.getExaParperClass().getId());
                    exaClassQuestionsService.insertExaClassQuestions(item1.getExaClassQuestions());
                });
            });
        }
        return R.ok();
    }

    /**
     *保存或编辑试卷管理
     */
    @ApiOperation("删除试卷管理")
    @DeleteMapping("/{parPerIds}")
    @Transactional
    public R deleteExaParPer(@PathVariable Long[] parPerIds){
        for (Long parPerId : parPerIds) {
            ExaParperClass exaParperClass = new ExaParperClass();
            exaParperClass.setParperId(parPerId);
            List<ExaParperClass> exaParperClasses = exaParperClassService.selectExaParperClassList(exaParperClass);
            exaParperClasses.forEach(item->{
                exaClassQuestionsService.deleteExaClassQuestionsByClassId(item.getId());
            });
            exaParperClassService.deleteExaParperClassByParperId(parPerId);
            exaParperService.deleteExaParperById(parPerId);
        }
        return R.ok();
    }

    /**
     *  新增或者修改答题卡
     *
     * @param exaBitchUserQuestionsVo 答题卡接收对象
     * @return 成功与否
     */
    @ApiOperation("新增或者修改答题卡")
    @PostMapping("/addOrUpdateUserQuestions")
    @Transactional
    public R addOrUpdateUserQuestions(@RequestBody ExaBitchUserQuestionsVo exaBitchUserQuestionsVo){
        if(exaBitchUserQuestionsVo.getType()==1){
            //修改  1
        }else {
            //保存答题卡之前先删除之前选的
            exaBitchUserQuestionsService.deleteExaBitchUserQuestionsOld(exaBitchUserQuestionsVo.getBitchId(),exaBitchUserQuestionsVo.getUserId(),exaBitchUserQuestionsVo.getParperId());
            ExaParper exaParper = exaParperService.selectExaParperById(exaBitchUserQuestionsVo.getParperId());
            //试卷总分
            AtomicReference<Long> scoreAll = new AtomicReference<>(0L);
            //新增  0
            //一套答题卡里有多个试题
            exaBitchUserQuestionsVo.getExaQuestionBankVos().forEach(topic->{
                //判断答案是否正确
                AtomicBoolean rorw = new AtomicBoolean(true);
                //试题可能会有多个答案
                ExaQuestionOptions exaQuestionOptions = new ExaQuestionOptions();
                exaQuestionOptions.setQuestionId(topic.getExaQuestionBank().getId());
                exaQuestionOptions.setRorw(true);
                List<ExaQuestionOptions> exaQuestionOptionsList = exaQuestionOptionsService.selectExaQuestionOptionsList(exaQuestionOptions);
                //多选中如果提交的答案与真实答案数量不一致直接判0分
                if(exaQuestionOptionsList.size()!=topic.getExaQuestionOptionsList().size()){
                    rorw.set(false);
                }
                topic.getExaQuestionOptionsList().forEach(answer->{
                    ExaQuestionOptions questionOptions = exaQuestionOptionsService.selectExaQuestionOptionsById(answer.getId());
                    if(!questionOptions.getRorw()){
                        rorw.set(false);
                    }
                    ExaBitchUserQuestions exaBitchUserQuestions = new ExaBitchUserQuestions();
                    exaBitchUserQuestions.setBitchId(exaBitchUserQuestionsVo.getBitchId());
                    exaBitchUserQuestions.setBitchName(exaBitchUserQuestionsVo.getBitchName());
                    exaBitchUserQuestions.setUserId(exaBitchUserQuestionsVo.getUserId());
                    exaBitchUserQuestions.setParperId(exaBitchUserQuestionsVo.getParperId());
                    exaBitchUserQuestions.setQuestionId(topic.getExaQuestionBank().getId());
                    exaBitchUserQuestions.setOptionsId(answer.getId());
                    exaBitchUserQuestions.setRorw(answer.getRorw());
                    exaBitchUserQuestions.setContent(answer.getContent());
                    exaBitchUserQuestionsService.insertExaBitchUserQuestions(exaBitchUserQuestions);
                });
                //提交试卷时只计算除简答题的试题
                if(!Objects.equals(topic.getExaQuestionBank().getType(), "4")){
                    //试题分数
                    Long score = topic.getExaQuestionBank().getScore();
                    if(rorw.get()){
                        scoreAll.set(scoreAll.get() + score);
                    }
                }
            });
            ExaBitchUser exaBitchUser = exaBitchUserService.selectExaBitchUserById(exaBitchUserQuestionsVo.getId());
            //判断是否是中途退出   0否 1是 2答题超时（不通过）
            Long remainingTime = exaBitchUserQuestionsVo.getRemainingTime();
            Long answeringTime = exaParper.getAnsweringTime();
            if(exaBitchUserQuestionsVo.getQuitStatus()==0){
                ExaParperClass exaParperClass = new ExaParperClass();
                exaParperClass.setParperId(exaBitchUserQuestionsVo.getParperId());
                List<ExaParperClass> exaParperClasses = iExaParperClassService.selectExaParperClassList(exaParperClass);
                List<ExaParperClass> collect = exaParperClasses.stream().filter(p -> p.getType().equals("4")).collect(Collectors.toList());
                //判断是否有简答题
                if(!collect.isEmpty()){
                    exaBitchUser.setIsPass("3");
                }else {
                    if(scoreAll.get()>=exaParper.getPassScore()){
                        exaBitchUser.setIsPass("1");
                    }else {
                        exaBitchUser.setIsPass("0");
                    }
                }
                exaBitchUser.setIsQuit(0);
                exaBitchUser.setScore(scoreAll.get());
                exaBitchUser.setCommitTime(DateUtils.getNowDate());
                //提交答题卡后变为已完成状态
                exaBitchUser.setStatus("2");
                exaBitchUser.setUserTime(answeringTime-remainingTime);
            }else if(exaBitchUserQuestionsVo.getQuitStatus()==1){
                exaBitchUser.setIsQuit(1);
                exaBitchUser.setRemainingTime(exaBitchUserQuestionsVo.getRemainingTime());
                exaBitchUser.setUserTime(answeringTime-remainingTime);
            } else if (exaBitchUserQuestionsVo.getQuitStatus()==2) {
                exaBitchUser.setIsPass("0");
                exaBitchUser.setStatus("3");
                exaBitchUser.setCommitTime(DateUtils.getNowDate());
            }
            exaBitchUserService.updateExaBitchUser(exaBitchUser);
        }
        return  R.ok();
    }

}
